/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package uk.ac.rdg.resc.mmd.controllers;

import java.io.InputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.HashMap;
import org.jdom.JDOMException;
import uk.ac.rdg.resc.mmd.diva.DivaWebService;

/**
 *
 * @author Alastair
 */
public class DivaController {

    private final String divaUrl = "http://gher-diva.phys.ulg.ac.be/web-vis/Python/web";

    private DivaWebService diva;
    private String sessionId;
    private String bbox;
    private String fieldname;

    public DivaController() {
        // Construct our DivaWebService object and upload the file from the ByteBuffer
        this.diva = new DivaWebService(divaUrl);
    }

    public InputStream getInterpolatedMapImage(InputStream dataIn) throws IOException, JDOMException {
        this.uploadData(dataIn);
        this.interpolate();
        InputStream wmsStream = diva.streamWMSMap(this.fieldname, this.bbox);
        return wmsStream;
    }

    public InputStream getInterpolatedNetcdf(InputStream dataIn) throws IOException, JDOMException {
        this.uploadData(dataIn);
        this.interpolate();
        InputStream netcdfStream = this.diva.streamNetcdf(this.fieldname);
        return netcdfStream;
    }

    private void uploadData(InputStream inputStream) throws IOException, JDOMException {
        HashMap<String, String> params = diva.upload(inputStream, "diva_input.txt");
        this.sessionId = params.get("sessionId");
        this.bbox = params.get("bbox");
    }

    private void interpolate() throws MalformedURLException, IOException, JDOMException {
        // Run the actual DIVA interpolation, and save the resulting fieldname from DIVA
        this.fieldname = diva.interpolate(this.sessionId, this.bbox);
    }
}